;
(function () {
  Array.prototype.removeRepeatBuildingAndFLoor = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  var withdrawAudit = new Vue({
    el: '#withdrawAudit',
    data: {
      data: {
        expenses: []
      },
      contratdata: {
        ot: [],
        st: []
      },
      billsno: null,
      billsId: null,
      zid: '',
      contractId: null,
      ywflag: true,
      cwflag: true,
      msgyw: '',
      msgcw: '',
      auditState: '',
      delFlag: false,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: true,
      wpOpenFlag: true,
      stOpenFlag: true,
      unitId: null, // 单元id
      unitDetailsFlag: false,
      unitDetailsState: false,
      withdrawList: ['退租详情', '账单信息', '相关文件'],
      widthFlagInfo: true,
      widthFlagFile: false,
      widthFlagbill: false,
      withdrawListAct: 0,
      projectId: null,
      permissions: JSON.parse(window.localStorage.getItem('permissions')),
      showCreateBill: false,
      progress: '',

      conflictBills: [],
    },
    filters: {
      formatDate: function (time) {
        if (time === undefined) {
          return '--'
        }
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
      formatNum: function (item) {
        if (item == '--') return '--'
        return hlNumberUtil.formatNum(item)
      },
      auditState: function (state) {
        return hlCodeConvert.withdrawAuditState(state)
      }
    },
    methods: {
      handleTabClick() {

      },
      //switchNav
      withdrawNav: function (i) {
        if (i == 0) {
          this.widthFlagInfo = true;
          this.widthFlagFile = false;
          this.widthFlagbill = false;
        }
        if (i == 1) {
          this.widthFlagbill = true;
          this.widthFlagInfo = false;
          this.widthFlagFile = false;

          // 如果是从退租单列表跳转而来，则直接从URL上获取退租单ID
          // 如果是从合同列表跳转而来，则从合同退租单中获取退租单ID
          if (hlUrlUtil.GetQueryString('id')) {
            progress.init(hlUrlUtil.GetQueryString('id'))
          }

        }
        if (i == 2) {
          this.widthFlagInfo = false;
          this.widthFlagFile = true;
          this.widthFlagbill = false;
        }
        this.withdrawListAct = i;
      },
      // 上传文件
      uploadFile: function () {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
      },
      //删除files
      delFiles: function (url, i) {
        var self = this;

        hlhttp.delete({
          url: 'withdraw_attachment?withdraw_id=' + self.zid + '&attachment_url=' + url,
          success: function () {
            hl.toast('删除成功')
            self.data.files.splice(i, 1)
          }
        })
      },
      // 获取合同单元信息
      getContractUnitsData: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/units',
          data: {
            id: self.contractId
          },
          success: function (data) {

            // 单元
            var buildingData = self.dealWithUnitData(data)
            self.totalArea = buildingData.totalArea
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.map(function (item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      // 单元数据去重整合处理
      dealWithUnitData: function (unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function (_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: [],
            unitId: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              unitArr[z].unitId.push(units[m].unitId)
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit,
                'unitId': unitArr[n].unitId
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 获取单元详情
      getUnitDetails: function (unitId) {
        var self = this;
        self.unitId = unitId;
        self.unitDetailsFlag = true;
      },
      closeUnitPop: function (state) {
        this.unitDetailsState = state ? true : false
        this.unitId = null;
        this.unitDetailsFlag = false;
      },
      // 查看出租资源详情信息
      checkDetailMes: function (type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      //删除合同
      delContract: function () {
        var _this = this;
        hlhttp.delete({
          url: 'withdraw?id=' + _this.withdrawId,
          success: function () {
            _this.delFlag = false;
            hl.toast('删除成功')
            hlUrlUtil.goTo('withdrawList', {
              ddtab: true
            })
          }
        })
      },
      getData: function () {
        if (window.location.href.indexOf('contractId') > -1) {
          var id = hlUrlUtil.GetQueryString('contractId')
          var _this = this;

          hlhttp.get({
            url: 'contract/withdraw',
            data: {
              contract_id: id
            },
            success: function (res) {
              _this.contractId = res.contractId;
              if (res.id) _this.zid = res.id;

              if (!res.id) {
                window.location.href = window.location.protocol+'//' + window.location.host + window.location.pathname + '#/withdrawCreate?id=' + id
                return
              }
              if (res.auditState == 'SCP') {
                window.location.href = window.location.protocol+'//' + window.location.host + window.location.pathname + '#/withdrawPlan?id=' + res.id
              }
              if (!res.files) {
                res.files = [];
                res.fileNames = [];
              }

              if (res.auditState == 'SCP' || res.auditState == 'WJS' || res.auditState == 'FN') {

                _this.showCreateBill = true
              }
              _this.data = res
              _this.auditState = res.auditState
              if (!res) {
                return
              }
              if (res.auditState == 'WJS') {
                _this.getbills(res.contractId)
              }

              loginPrem.loginList()
              _this.zid = res.id

              contract.formatUnitData(res.contractId, function (data) {
                _this.contratdata = data
              })
              _this.getContractUnitsData()
              progress.init(res.id)

            }
          })
        } else {
          var _this = this;
          var id = hlUrlUtil.GetQueryString('id')
          this.zid = id;
          hlhttp.get({
            url: 'withdraw,expenses',
            data: {
              id: id
            },
            success: function (res) {
              res.conflictBills.map(item => {
                item.expenses.map(single => {
                  if (single.withdrawAmount) {
                    single.withdrawAmount.amountRefund = (Number(single.withdrawAmount.amountPayed) + Number(single.withdrawAmount.derateExpense) + Number(single.withdrawAmount.carryOverAmount) - Number(single.withdrawAmount.amountReceive)).toFixed(2)
                  }
                  if (single.amount) {
                    single.amount.amountRefund = (Number(single.amount.amountPayed) + Number(single.amount.derateExpense) + Number(single.amount.carryOverAmount) - Number(single.amount.amountReceive)).toFixed(2)
                  }
                })
              })
              console.log(res.conflictBills)
              
              _this.conflictBills = res.conflictBills;
              _this.contractId = res.contractId;

              if (res.auditState == 'SCP' || res.auditState == 'WJS' || res.auditState == 'FN') {

                _this.showCreateBill = true
              }
              loginPrem.loginList()
              if (!res.files) {
                res.files = [];
                res.fileNames = [];
              }
              _this.data = res
              if (!res) {
                return
              }
              if (res.auditState == 'WJS') {
                _this.getbills(res.contractId)
              }
              loginPrem.loginList()
              contract.formatUnitData(res.contractId, function (data) {
                _this.contratdata = data
              })
              _this.getContractUnitsData()
            }
          })
        }
      },
      //获取待结算
      getbills: function (id) {
        var _this = this;
        hlhttp.get({
          url: 'contracts/bills',
          data: {
            contract_id: id
          },
          success: function (res) {
            for (var i = 0; i < res.length; i++) {
              if (res[i].source == 'T') {
                _this.billsno = res[i].no;
                _this.billsId = res[i].id;
              }
            }
          }
        })
      },
      //作废
      invalid: function () {
        var id = this.zid;
        var _this = this;
        hllayer.confirm1('你确定要作废退租单吗？',
          function () {
            hlhttp.put({
              url: 'withdraw/zf',
              data: {
                id: id
              },
              success: function () {
                hl.toast('作废成功')
                _this.getData()
              }
            })
          }
        )
      },
      //财务审核通过
      FinWCPAudit: function () {
        var id = this.zid;
        var _this = this;
        hllayer.confirm1('确认审核通过，返回取消',
          function () {
            hlhttp.put({
              url: 'withdraw/pcp',
              data: {
                id: id
              },
              success: function () {
                hl.toast('财务审核通过')
                _this.getData()
              }
            })
          }
        )
      },
      //财务不审核通过
      FinWCPnAudit: function () {
        var id = this.zid;
        var _this = this;
        hlhttp.put({
          url: 'withdraw/fcp',
          data: {
            id: id,
            reason: _this.msgcw || '#'
          },
          success: function () {
            hl.toast('财务不审核通过')
            _this.cwflag = true;
            _this.getData()
          }
        })
      },
      //业务审核通过
      FinWBPAudit: function () {
        var id = this.zid;
        var _this = this;
        hllayer.confirm1('确认审核通过，返回取消',
          function () {
            hlhttp.put({
              url: 'withdraw/pbp',
              data: {
                id: id
              },
              success: function () {
                hl.toast('业务审核通过')
                _this.getData()
              }
            })
          }
        )
      },
      //业务审核拒绝
      FinWBPnAudit: function () {
        var id = this.zid;
        var _this = this;
        hlhttp.put({
          url: 'withdraw/fbp',
          data: {
            id: id,
            reason: _this.msgyw || '#'
          },
          success: function () {
            hl.toast('业务审核拒绝')
            _this.ywflag = true;
            _this.getData()
          }
        })
      },
      //合同终止校验
      checkWithout() {
        var that = this
        hlhttp.get({
          url: 'withdraw/_check',
          data: {
            'contract_id': that.contractId
          },
          success: function (res) {
            that.FinWBPsnAudit()
          },
        })
      },
      //提交业务审核
      FinWBPsnAudit: function () {
        var id = this.zid;
        var _this = this;
        hlhttp.put({
          url: 'bpm/check_project_use',
          data: {
            bpm_key: 'WT',
            project_id: _this.contratdata.projectId
          },
          success: function (res) {
            if (res.flag == 'N') {
              hl.toast('请先配置流程')
              return
            }
            rois()
          }
        })

        function rois() {
          hllayer.confirm1('确认提交审核，返回取消',
            function () {
              hlhttp.put({
                url: 'withdraw/wbp',
                data: {
                  id: id
                },
                success: function () {
                  hl.toast('提交业务审核成功')
                  setTimeout(function () {
                    hlUrlUtil.goTo('withdrawList', {
                      ddtab: true
                    })
                  }, 200)
                }
              })
            })
        }
      },
      //提交财务审核
      FinWBPssnAudit: function () {
        var id = this.zid;
        var _this = this;
        hllayer.confirm1('提交业务审核，返回取消',
          function () {
            hlhttp.put({
              url: 'withdraw/wcp',
              data: {
                id: id
              },
              success: function () {
                hl.toast('提交财务审核成功')
                _this.getData()
              }
            })
          }
        )
      },
      //ywhide
      ywshowhide: function (flag) {
        this.ywflag = flag
      },
      //cwshowhide
      cwshowhide: function (flag) {
        this.cwflag = flag
      },
      //大图
      bigPicShow: function (arr, i) {
        $.imageShow(arr, i)
      },
      previewImage: function (url) {
        var imageExt = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'];
        var pdfExt = ['pdf', 'PDF'];
        var officeExt = ['docx', 'doc', 'xlsx', 'xls', 'xlt']
        var imageFlag = false;
        var pdfFlag = false;
        var officeFlag = false;

        imageExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) imageFlag = true;
        })

        if (imageFlag) {
          $.imageShow([url])
          return
        }
        pdfExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) pdfFlag = true;
        })
        if (pdfFlag) {
          $.previewPDF(url)
          return
        }

        officeExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) officeFlag = true
        })
        if (officeFlag) {
          $.previewOffice(url)
          return
        }
        hl.toast('暂不支持该格式')
      },
      createBill() {
        hlUrlUtil.goTo('createBill', {
          'page': 'billList',
          ddtab: true,
          'code': this.data.wCode,
          'type': 'TZ',
          'name': escape(this.contratdata.zlfCompany),
          'HTname': escape(this.contratdata.contractName)
        })
      }
    },
    created() {
      if (this.permissions.indexOf('c127') == -1) {
        this.withdrawList = ['退租详情', '账单信息']
      }
    },
    mounted: function () {
      this.getData()
      var self = this;
      fileUpload('.upload-files', uploadUrl, function (src) {
        self.progress = ''
        if (src.json == undefined) return;

        hlhttp.post({
          url: 'withdraw_attachment',
          data: {
            withdraw_id: hlUrlUtil.GetQueryString('id') || self.zid,
            attachment_name: src.json.name,
            attachment_url: src.json.url
          },
          success: function () {
            hl.toast('上传成功')
            self.data.files.push(src.json.url)
            self.data.fileNames.push(src.json.name)
          }
        })
      }, function (val) {
        self.progress = parseInt((val.loaded / val.total) * 100) + '%'
      })
    }
  })
}())